package org.x.note.thread;

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 放号器, 多个线程同时申请号码不重复,断电后能恢复. <br>
 * 比如: <br>
 * 线程1 : 1, 4, 5, 6, 8, 9, 14…<br>
 * 线程2 : 2, 3, 7, 10, 11, 12, 13…
 * 
 * @author xyl
 * 
 */
public class SendCode implements Runnable {
	private int code;
	private RandomAccessFile raf = null;

	{
		try {
			raf = new RandomAccessFile("code.txt", "rw");
			code = raf.readInt();
			System.out.println("断点恢复号码:" + code);
		} catch (IOException e) {
			System.out.println("第一次放号初始化......");
		}
	}

	public void run() {
		while (true) {
			synchronized (this) {
				try {
					raf.seek(0);
					Thread.sleep(500);
					code++;
					raf.writeInt(code);
					System.out.println(Thread.currentThread().getName()
							+ "申请号码:" + code);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
	}

	public static void main(String[] args) {
		SendCode sc = new SendCode();
		new Thread(sc, "线程1").start();
		new Thread(sc, "线程2").start();
	}
}